import {useState, useEffect} from 'react'

export default (targetKeyCode) => {
  const [keyPressed, setKeyPressed] = useState(false)

  const keyDownHandler = ({keyCode}) => {
    keyCode === targetKeyCode && setKeyPressed(true)
  }

  const keyUpHandler = ({keyCode}) => {
    keyCode === targetKeyCode && setKeyPressed(false)
  }

  useEffect(() => {
    document.addEventListener('keydown', keyDownHandler)
    document.addEventListener('keyup', keyUpHandler)

    return () => {
      document.removeEventListener('keydown', keyDownHandler)
      document.removeEventListener('keyup', keyUpHandler)
    }
  }, [])

  return keyPressed
}
